var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { getExportMap } from './getExportMap.js';
import { resolveImport } from './resolveImport/index.js';
export const resolveAllImports = (params) => __awaiter(void 0, void 0, void 0, function* () {
    const { snippets, fileWithImports } = params;
    let content = fileWithImports.content;
    const exportMap = getExportMap(content);
    for (const source of Object.keys(fileWithImports.importMap)) {
        if (!source.startsWith('/snippets/')) {
            console.log(`Invalid import path ${source} in ${fileWithImports.filename}. Import source must start with "/snippets/".`);
            continue;
        }
        const importedSnippet = snippets.find((snippet) => snippet.filename === source);
        if (importedSnippet == undefined) {
            console.log(`Could not find file ${source} - imported from ${fileWithImports.filename}`);
            continue;
        }
        const specifiers = fileWithImports.importMap[source];
        if (specifiers == undefined)
            continue;
        for (const specifier of specifiers) {
            try {
                yield resolveImport(specifier, content, importedSnippet.content, exportMap).then((contentWithResolvedImport) => {
                    if (contentWithResolvedImport == undefined)
                        throw new Error('Import failed to resolve');
                    content = contentWithResolvedImport;
                });
            }
            catch (err) {
                console.log(`Error resolving import "${specifier.name}" in ${fileWithImports.filename}`);
                console.log(err);
            }
        }
    }
    return content;
});
